<template>
  <div>
    <button @click="addItem">添加项目</button>
    <button @click="removeItem">删除最后一项</button>

    <transition-group name="list" tag="ul" class="plain-list">
      <li
        v-for="(item, index) in items"
        :key="item.id"
        :class="{ 'new-item': item.isNew }"
      >
        {{ item.text }}
      </li>
    </transition-group>
  </div>
</template>
<script setup>
import { ref } from 'vue'
/* 初始列表 */
const items = ref([
  { id: 1, text: '项目1 (索引: 0)' },
  { id: 2, text: '项目2 (索引: 1)' },
  { id: 3, text: '项目3 (索引: 2)' }
])
/* 添加 */
const addItem = () => {
  const newId = Date.now()
  const newIndex = items.value.length
  const newItem = {
    id: newId,
    text: `项目${newIndex + 1} (索引: ${newIndex})`,
    isNew: true
  }
  items.value.push(newItem)
  // 1 秒后去掉高亮
  setTimeout(() => {
    const item = items.value.find(i => i.id === newId)
    if (item) item.isNew = false
  }, 1000)
}
/* 删除最后一项 */
const removeItem = () => {
  if (items.value.length) items.value.shift()
}
</script>
<style scoped>
/* 去黑点 */
.plain-list {
  list-style: none;
  padding-left: 0;
  margin: 0;
}
/* 每项背景 */
.plain-list li {
  background: #f0f0f0;
  margin: 4px 0;
  padding: 6px 10px;
  border-radius: 4px;
}
/* 新增高亮 */
.new-item {
  background: #d4edda !important;
  transition: background 1s ease;
}
/* 动画 */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from {
  opacity: 0;
  transform: translateX(30px);
}
.list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style>